{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 包的导入\n",
    "与以前的相比，主要增加了简繁转换的包zhconv，变长序列处理的pad_sequence, pack_padded_sequence, pad_packed_sequence等"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import os\n",
    "import random\n",
    "import re #split使用\n",
    "import gensim # word2vec预训练加载 \n",
    "import jieba #分词\n",
    "from torch import nn \n",
    "import numpy as np \n",
    "from torch.utils.data import Dataset,DataLoader\n",
    "import torch.optim as optim\n",
    "from torch.utils.tensorboard import SummaryWriter \n",
    "from tqdm.notebook import tqdm\n",
    "from zhconv import convert #简繁转换\n",
    "# 变长序列的处理\n",
    "from torch.nn.utils.rnn import pad_sequence,pack_padded_sequence,pad_packed_sequence\n",
    "# from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 参数配置\n",
    "这里为了使用预训练的中文维基词向量，必须将embedding层的维度设置为50维以和预训练权重匹配，其他的参数如dropout 概率，层数等都可以自定以"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class DictObj(object):\n",
    "    # 私有变量是map\n",
    "    # 设置变量的时候 初始化设置map\n",
    "    def __init__(self, mp):\n",
    "        self.map = mp\n",
    "        # print(mp)\n",
    "\n",
    "# set 可以省略 如果直接初始化设置，而不在程序中修改配置的话\n",
    "    def __setattr__(self, name, value):\n",
    "        if name == 'map':# 初始化的设置 走默认的方法\n",
    "            # print(\"init set attr\", name ,\"value:\", value)\n",
    "            object.__setattr__(self, name, value)\n",
    "            return\n",
    "        # print('set attr called ', name, value)\n",
    "        self.map[name] = value\n",
    "# 之所以自己新建一个类就是为了能够实现直接调用名字的功能。\n",
    "    def __getattr__(self, name):\n",
    "        # print('get attr called ', name)\n",
    "        return  self.map[name]\n",
    "\n",
    "\n",
    "Config = DictObj({\n",
    "    'train_path' : \"D:/AIdata/Sentiment-classification/Dataset/train.txt\",\n",
    "    'test_path' : \"D:/AIdata/Sentiment-classification/Dataset/test.txt\",\n",
    "    'validation_path' : \"D:/AIdata/Sentiment-classification/Dataset/validation.txt\",\n",
    "    'pred_word2vec_path':'D:/AIdata/Sentiment-classification/Dataset/wiki_word2vec_50.bin',\n",
    "    'tensorboard_path':'./tensorboard',\n",
    "    'model_save_path':'./modelDict/model.pth',\n",
    "    'embedding_dim':50,\n",
    "    'hidden_dim':100,\n",
    "    'lr':0.001,\n",
    "    'LSTM_layers':3,\n",
    "    'drop_prob': 0.5,\n",
    "    'seed':0\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据集构建\n",
    "### 词汇表建立\n",
    "首先建立训练数据的词汇表，实现汉字转索引。构建词汇表的逻辑：首先读取训练集的数据，然后使用zhconv包统一转换成简体，\n",
    "因为数据集本身就已经是分词后的数据了，只需要对应的读入这些词汇然后去重，之后根据去重的list构建两个word2ix 和ix2word即可。\n",
    "\n",
    "这里思路比较简单，但是有个坑，导致我调了一天的bug。就是每次set操作后对应的顺序是不同的，因为我没有将词汇表保存下来，想的是每次程序运行的时候再来重新构建，因此每次重新set之后得到的词汇表也是不一致的，导致同样的语言文本经过不同的词汇表转换后，每次都得到不同的输入，\n",
    "因此导致训练好的模型每次重新加载kernel之后得到的测试集准确率都不一样。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 简繁转换 并构建词汇表\n",
    "def build_word_dict(train_path):\n",
    "    words = []\n",
    "    max_len = 0\n",
    "    total_len = 0\n",
    "    with open(train_path,'r',encoding='UTF-8') as f:\n",
    "        lines = f.readlines()\n",
    "        for line in  lines:\n",
    "            line = convert(line, 'zh-cn') #转换成大陆简体\n",
    "            line_words = re.split(r'[\\s]', line)[1:-1] # 按照空字符\\t\\n 空格来切分\n",
    "            max_len = max(max_len, len(line_words))\n",
    "            total_len += len(line_words)\n",
    "            for w in line_words:\n",
    "                words.append(w)\n",
    "    words = list(set(words))#最终去重\n",
    "    words = sorted(words) # 一定要排序不然每次读取后生成此表都不一致，主要是set后顺序不同\n",
    "    #用unknown来表示不在训练语料中的词汇\n",
    "    word2ix = {w:i+1 for i,w in enumerate(words)} # 第0是unknown的 所以i+1\n",
    "    ix2word = {i+1:w for i,w in enumerate(words)}\n",
    "    word2ix['<unk>'] = 0\n",
    "    ix2word[0] = '<unk>'\n",
    "    avg_len = total_len / len(lines)\n",
    "    return word2ix, ix2word, max_len,  avg_len"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "word2ix, ix2word, max_len, avg_len = build_word_dict(Config.train_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "679 44.67896789678968\n"
     ]
    }
   ],
   "source": [
    "print(max_len, avg_len)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数据变长处理\n",
    "输入样本的中，词汇的长度不一致，最大的长度有679个词，平均而言只有44个词，所以如果只是单纯的填0来进行维度统一的话，大量的0填充会让模型产生误差，\n",
    "参考[忆臻文章](https://zhuanlan.zhihu.com/p/34418001)中的图片：![](https://pic3.zhimg.com/80/v2-b0aab81f3e671fad36761203c4b5df2a_720w.jpg) \n",
    "\n",
    "\n",
    "为了处理这种情况需要将序列长度不一致的样本，根据长度排序后进行按照批次来分别填充，详细介绍参考[尹相楠的文章](https://zhuanlan.zhihu.com/p/59772104) 和[腾仔的文章](https://zhuanlan.zhihu.com/p/70822702), 在这不赘述。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mycollate_fn(data):\n",
    "    # 这里的data是getittem返回的（input，label）的二元组，总共有batch_size个\n",
    "    data.sort(key=lambda x: len(x[0]), reverse=True)  # 根据input来排序\n",
    "    data_length = [len(sq[0]) for sq in data]\n",
    "    input_data = []\n",
    "    label_data = []\n",
    "    for i in data:\n",
    "        input_data.append(i[0])\n",
    "        label_data.append(i[1])\n",
    "    input_data = pad_sequence(input_data, batch_first=True, padding_value=0)\n",
    "    label_data = torch.tensor(label_data)\n",
    "    return input_data, label_data, data_length"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "数据集的类里面主要是获取数据和标签，稍微需要注意的是考虑到测试集和验证集中一些不会在训练语料库中出现的词汇，需要将这些词汇置为0，来避免索引错误"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "class CommentDataSet(Dataset):\n",
    "    def __init__(self, data_path, word2ix, ix2word):\n",
    "        self.data_path = data_path\n",
    "        self.word2ix = word2ix\n",
    "        self.ix2word = ix2word\n",
    "        self.data, self.label = self.get_data_label()\n",
    "\n",
    "    def __getitem__(self, idx: int):\n",
    "        return self.data[idx], self.label[idx]\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.data)\n",
    "\n",
    "    def get_data_label(self):\n",
    "        data = []\n",
    "        label = []\n",
    "        with open(self.data_path, 'r', encoding='UTF-8') as f:\n",
    "            lines = f.readlines()\n",
    "            for line in lines:\n",
    "                try:\n",
    "                    label.append(torch.tensor(int(line[0]), dtype=torch.int64))\n",
    "                except BaseException:  # 遇到首个字符不是标签的就跳过比如空行，并打印\n",
    "                    print('not expected line:' + line)\n",
    "                    continue\n",
    "                line = convert(line, 'zh-cn')  # 转换成大陆简体\n",
    "                line_words = re.split(r'[\\s]', line)[1:-1]  # 按照空字符\\t\\n 空格来切分\n",
    "                words_to_idx = []\n",
    "                for w in line_words:\n",
    "                    try:\n",
    "                        index = self.word2ix[w]\n",
    "                    except BaseException:\n",
    "                        index = 0  # 测试集，验证集中可能出现没有收录的词语，置为0\n",
    "                    #                 words_to_idx = [self.word2ix[w] for w in line_words]\n",
    "                    words_to_idx.append(index)\n",
    "                data.append(torch.tensor(words_to_idx, dtype=torch.int64))\n",
    "        return data, label"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 训练集，验证集，测试集，加载"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "not expected line:\n",
      "\n",
      "not expected line:\n",
      "\n"
     ]
    }
   ],
   "source": [
    "train_data = CommentDataSet(Config.train_path, word2ix, ix2word)\n",
    "train_loader = DataLoader(train_data, batch_size=16, shuffle=True,\n",
    "                         num_workers=0, collate_fn=mycollate_fn,)\n",
    "\n",
    "validation_data = CommentDataSet(Config.validation_path, word2ix, ix2word)\n",
    "validation_loader = DataLoader(validation_data, batch_size=16, shuffle=True,\n",
    "                         num_workers=0, collate_fn=mycollate_fn,)\n",
    "\n",
    "test_data = CommentDataSet(Config.test_path, word2ix, ix2word)\n",
    "test_loader = DataLoader(test_data, batch_size=16, shuffle=False,\n",
    "                         num_workers=0, collate_fn=mycollate_fn,)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##  预训练权重加载\n",
    "这里需要将预训练的中文word2vec的权重初始到pytorch embedding层，主要的逻辑思路首先使用gensim包来加载权重，然后根据前面建立的词汇表，初始一个vocab_size*embedding_dim的0矩阵weight，之后对每个词汇查询是否在预训练的word2vec中有权重，如果有的话就将这个权重复制到weight中，最后使用weight来初始embedding层就可以了。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# word2vec加载\n",
    "word2vec_model = gensim.models.KeyedVectors.load_word2vec_format(Config.pred_word2vec_path, binary=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(426677, 50)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#50维的向量\n",
    "word2vec_model.__dict__['vectors'].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pre_weight(vocab_size):\n",
    "    weight = torch.zeros(vocab_size,Config.embedding_dim)\n",
    "    #初始权重\n",
    "    for i in range(len(word2vec_model.index2word)):#预训练中没有word2ix，所以只能用索引来遍历\n",
    "        try:\n",
    "            index = word2ix[word2vec_model.index2word[i]]#得到预训练中的词汇的新索引\n",
    "        except:\n",
    "            continue\n",
    "        weight[index, :] = torch.from_numpy(word2vec_model.get_vector(\n",
    "            ix2word[word2ix[word2vec_model.index2word[i]]]))#得到对应的词向量\n",
    "    return weight"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 模型构建\n",
    "模型的构建与前面的[LSTM自动写诗](https://zhuanlan.zhihu.com/p/138270447)大体一致,即embedding后LSTM层然后3层全连接，激活函数选择了tanh。不同的点在于，这里的输出只保留时间步的最后一步，用来当作预测结果。也就是最后一个全连接层的输出取最后一个时间步的输出。以及为了防止过拟合而采用了Dropout"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SentimentModel(nn.Module):\n",
    "    def __init__(self, embedding_dim, hidden_dim,pre_weight):\n",
    "        super(SentimentModel, self).__init__()\n",
    "        self.hidden_dim = hidden_dim\n",
    "        self.embeddings = nn.Embedding.from_pretrained(pre_weight)\n",
    "        # requires_grad指定是否在训练过程中对词向量的权重进行微调\n",
    "        self.embeddings.weight.requires_grad = True\n",
    "        self.lstm = nn.LSTM(embedding_dim, self.hidden_dim, num_layers=Config.LSTM_layers,\n",
    "                            batch_first=True, dropout=Config.drop_prob, bidirectional=False)\n",
    "        self.dropout = nn.Dropout(Config.drop_prob)\n",
    "        self.fc1 = nn.Linear(self.hidden_dim,256)\n",
    "        self.fc2 = nn.Linear(256,32)\n",
    "        self.fc3 = nn.Linear(32,2)\n",
    "#         self.linear = nn.Linear(self.hidden_dim, vocab_size)# 输出的大小是词表的维度，\n",
    "\n",
    "    def forward(self, input, batch_seq_len, hidden=None):\n",
    "        embeds = self.embeddings(input)  # [batch, seq_len] => [batch, seq_len, embed_dim]\n",
    "        embeds = pack_padded_sequence(embeds,batch_seq_len, batch_first=True)\n",
    "        batch_size, seq_len = input.size()\n",
    "        if hidden is None:\n",
    "            h_0 = input.data.new(Config.LSTM_layers*1, batch_size, self.hidden_dim).fill_(0).float()\n",
    "            c_0 = input.data.new(Config.LSTM_layers*1, batch_size, self.hidden_dim).fill_(0).float()\n",
    "        else:\n",
    "            h_0, c_0 = hidden\n",
    "        output, hidden = self.lstm(embeds, (h_0, c_0))#hidden 是h,和c 这两个隐状态\n",
    "        output,_ = pad_packed_sequence(output,batch_first=True)\n",
    "        \n",
    "        output = self.dropout(torch.tanh(self.fc1(output)))\n",
    "        output = torch.tanh(self.fc2(output))\n",
    "        output = self.fc3(output)\n",
    "        last_outputs = self.get_last_output(output, batch_seq_len)\n",
    "#         output = output.reshape(batch_size * seq_len, -1)\n",
    "        return last_outputs,hidden\n",
    "    def get_last_output(self,output,batch_seq_len):\n",
    "        last_outputs = torch.zeros((output.shape[0],output.shape[2]))\n",
    "        for i in range(len(batch_seq_len)):\n",
    "            last_outputs[i] =  output[i][batch_seq_len[i]-1]#index 是长度 -1\n",
    "        last_outputs = last_outputs.to(output.device)\n",
    "        return last_outputs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 准确率指标\n",
    "分别有两个指标一个是topk的AverageMeter，另一个是使用混淆矩阵。混淆矩阵的实现的时候先转为(pred, label)的二元对，然后相应的填充到表中。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "class AvgrageMeter(object):\n",
    "\n",
    "    def __init__(self):\n",
    "        self.reset()\n",
    "\n",
    "    def reset(self):\n",
    "        self.avg = 0\n",
    "        self.sum = 0\n",
    "        self.cnt = 0\n",
    "\n",
    "    def update(self, val, n=1):\n",
    "        self.sum += val * n\n",
    "        self.cnt += n\n",
    "        self.avg = self.sum / self.cnt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "#混淆矩阵指标\n",
    "class ConfuseMeter(object):\n",
    "\n",
    "    def __init__(self):\n",
    "        self.reset()\n",
    "\n",
    "    def reset(self):\n",
    "        # 标签的分类：0 pos 1 neg \n",
    "        self.confuse_mat = torch.zeros(2,2)\n",
    "        self.tp = self.confuse_mat[0,0]\n",
    "        self.fp = self.confuse_mat[0,1]\n",
    "        self.tn = self.confuse_mat[1,1]\n",
    "        self.fn = self.confuse_mat[1,0]\n",
    "        self.acc = 0\n",
    "        self.pre = 0\n",
    "        self.rec = 0\n",
    "        self.F1 = 0\n",
    "    def update(self, output, label):\n",
    "        pred = output.argmax(dim = 1)\n",
    "        for l, p in zip(label.view(-1),pred.view(-1)):\n",
    "            self.confuse_mat[p.long(), l.long()] += 1 # 对应的格子加1\n",
    "        self.tp = self.confuse_mat[0,0]\n",
    "        self.fp = self.confuse_mat[0,1]\n",
    "        self.tn = self.confuse_mat[1,1]\n",
    "        self.fn = self.confuse_mat[1,0]\n",
    "        self.acc = (self.tp+self.tn) / self.confuse_mat.sum()\n",
    "        self.pre = self.tp / (self.tp + self.fp)\n",
    "        self.rec = self.tp / (self.tp + self.fn)\n",
    "        self.F1 = 2 * self.pre*self.rec / (self.pre + self.rec)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "## topk的准确率计算\n",
    "def accuracy(output, label, topk=(1,)):\n",
    "    maxk = max(topk) \n",
    "    batch_size = label.size(0)\n",
    "    \n",
    "    # 获取前K的索引\n",
    "    _, pred = output.topk(maxk, 1, True, True) #使用topk来获得前k个的索引\n",
    "    pred = pred.t() # 进行转置\n",
    "    # eq按照对应元素进行比较 view(1,-1) 自动转换到行为1,的形状， expand_as(pred) 扩展到pred的shape\n",
    "    # expand_as 执行按行复制来扩展，要保证列相等\n",
    "    correct = pred.eq(label.view(1, -1).expand_as(pred)) # 与正确标签序列形成的矩阵相比，生成True/False矩阵\n",
    "#     print(correct)\n",
    "\n",
    "    rtn = []\n",
    "    for k in topk:\n",
    "        correct_k = correct[:k].view(-1).float().sum(0) # 前k行的数据 然后平整到1维度，来计算true的总个数\n",
    "        rtn.append(correct_k.mul_(100.0 / batch_size)) # mul_() ternsor 的乘法  正确的数目/总的数目 乘以100 变成百分比\n",
    "    return rtn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 训练函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "#一个epoch的训练逻辑\n",
    "def train(epoch,epochs, train_loader, device, model, criterion, optimizer,scheduler,tensorboard_path):\n",
    "    model.train()\n",
    "    top1 = AvgrageMeter()\n",
    "    model = model.to(device)\n",
    "    train_loss = 0.0\n",
    "    for i, data in enumerate(train_loader, 0):  # 0是下标起始位置默认为0\n",
    "        inputs, labels, batch_seq_len = data[0].to(device), data[1].to(device), data[2]\n",
    "        # 初始为0，清除上个batch的梯度信息\n",
    "        optimizer.zero_grad()\n",
    "        outputs,hidden = model(inputs,batch_seq_len)\n",
    "\n",
    "        loss = criterion(outputs,labels)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        _,pred = outputs.topk(1)\n",
    "        prec1, prec2= accuracy(outputs, labels, topk=(1,2))\n",
    "        n = inputs.size(0)\n",
    "        top1.update(prec1.item(), n)\n",
    "        train_loss += loss.item()\n",
    "        postfix = {'train_loss': '%.6f' % (train_loss / (i + 1)), 'train_acc': '%.6f' % top1.avg}\n",
    "        train_loader.set_postfix(log=postfix)\n",
    "\n",
    "        # ternsorboard 曲线绘制\n",
    "        if os.path.exists(tensorboard_path) == False: \n",
    "            os.mkdir(tensorboard_path)    \n",
    "        writer = SummaryWriter(tensorboard_path)\n",
    "        writer.add_scalar('Train/Loss', loss.item(), epoch)\n",
    "        writer.add_scalar('Train/Accuracy', top1.avg, epoch)\n",
    "        writer.flush()\n",
    "    scheduler.step()\n",
    "\n",
    "#     print('Finished Training')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 验证函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "def validate(epoch,validate_loader, device, model, criterion, tensorboard_path):\n",
    "    val_acc = 0.0\n",
    "    model = model.to(device)\n",
    "    model.eval()\n",
    "    with torch.no_grad():  # 进行评测的时候网络不更新梯度\n",
    "        val_top1 = AvgrageMeter()\n",
    "        validate_loader = tqdm(validate_loader)\n",
    "        validate_loss = 0.0\n",
    "        for i, data in enumerate(validate_loader, 0):  # 0是下标起始位置默认为0\n",
    "            inputs, labels, batch_seq_len = data[0].to(device), data[1].to(device), data[2]\n",
    "            #         inputs,labels = data[0],data[1]\n",
    "            outputs,_ = model(inputs, batch_seq_len)\n",
    "            loss = criterion(outputs, labels)\n",
    "\n",
    "            prec1, prec2 = accuracy(outputs, labels, topk=(1, 2))\n",
    "            n = inputs.size(0)\n",
    "            val_top1.update(prec1.item(), n)\n",
    "            validate_loss += loss.item()\n",
    "            postfix = {'validate_loss': '%.6f' % (validate_loss / (i + 1)), 'validate_acc': '%.6f' % val_top1.avg}\n",
    "            validate_loader.set_postfix(log=postfix)\n",
    "            \n",
    "            # ternsorboard 曲线绘制\n",
    "            if os.path.exists(tensorboard_path) == False: \n",
    "                os.mkdir(tensorboard_path)    \n",
    "            writer = SummaryWriter(tensorboard_path)\n",
    "            writer.add_scalar('Validate/Loss', loss.item(), epoch)\n",
    "            writer.add_scalar('Validate/Accuracy', val_top1.avg, epoch)\n",
    "            writer.flush()\n",
    "        val_acc = val_top1.avg\n",
    "    return val_acc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def test(validate_loader, device, model, criterion):\n",
    "    val_acc = 0.0\n",
    "    model = model.to(device)\n",
    "    model.eval()\n",
    "    confuse_meter = ConfuseMeter()\n",
    "    with torch.no_grad():  # 进行评测的时候网络不更新梯度\n",
    "        val_top1 = AvgrageMeter()\n",
    "        validate_loader = tqdm(validate_loader)\n",
    "        validate_loss = 0.0\n",
    "        for i, data in enumerate(validate_loader, 0):  # 0是下标起始位置默认为0\n",
    "            inputs, labels, batch_seq_len = data[0].to(device), data[1].to(device), data[2]\n",
    "            #         inputs,labels = data[0],data[1]\n",
    "            outputs,_ = model(inputs, batch_seq_len)\n",
    "#             loss = criterion(outputs, labels)\n",
    "\n",
    "            prec1, prec2 = accuracy(outputs, labels, topk=(1, 2))\n",
    "            n = inputs.size(0)\n",
    "            val_top1.update(prec1.item(), n)\n",
    "            confuse_meter.update(outputs, labels)\n",
    "#             validate_loss += loss.item()\n",
    "            postfix = { 'test_acc': '%.6f' % val_top1.avg,\n",
    "                      'confuse_acc': '%.6f' % confuse_meter.acc}\n",
    "            validate_loader.set_postfix(log=postfix)\n",
    "        val_acc = val_top1.avg\n",
    "    return confuse_meter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 随机数种子设置\n",
    "随机种子的设置需要在模型初始之前，这样才能保证模型每次初始化的时候得到的是一样的权重，从而保证能够复现每次训练结果\n",
    "`torch.backends.cudnn.benchmark = True ` 参考 https://zhuanlan.zhihu.com/p/73711222"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def set_seed(seed):\n",
    "    # seed\n",
    "    np.random.seed(seed)\n",
    "    random.seed(seed)\n",
    "    torch.manual_seed(seed)\n",
    "    if torch.cuda.is_available():\n",
    "        torch.cuda.manual_seed_all(seed)  #并行gpu\n",
    "        torch.backends.cudnn.deterministic = True  #cpu/gpu结果一致\n",
    "#         torch.backends.cudnn.benchmark = True   #训练集变化不大时使训练加速   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "set_seed(Config.seed)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 模型初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = SentimentModel(embedding_dim=Config.embedding_dim,\n",
    "                      hidden_dim=Config.hidden_dim,\n",
    "                      pre_weight=pre_weight(len(word2ix)))\n",
    "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
    "epochs = 3\n",
    "optimizer = optim.Adam(model.parameters(), lr=Config.lr)\n",
    "scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size = 10,gamma=0.1)#学习率调整\n",
    "criterion = nn.CrossEntropyLoss()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SentimentModel(\n",
       "  (embeddings): Embedding(51406, 50)\n",
       "  (lstm): LSTM(50, 100, num_layers=3, batch_first=True, dropout=0.5)\n",
       "  (dropout): Dropout(p=0.5, inplace=False)\n",
       "  (fc1): Linear(in_features=100, out_features=256, bias=True)\n",
       "  (fc2): Linear(in_features=256, out_features=32, bias=True)\n",
       "  (fc3): Linear(in_features=32, out_features=2, bias=True)\n",
       ")"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 迭代训练\n",
    "在每个epoch中同时收集验证集准确率，防止过拟合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "#因为使用tensorboard画图会产生很多日志文件，这里进行清空操作\n",
    "import shutil  \n",
    "if os.path.exists(Config.tensorboard_path):\n",
    "    shutil.rmtree(Config.tensorboard_path)  \n",
    "    os.mkdir(Config.tensorboard_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "训练时win10+Pytorch1.3会出现随机的bug，RuntimeError: cuda runtime error (719) : unspecified launch failure at C:/w/1/s/tmp_conda_3.6_081743/conda/conda-bld/pytorch_1572941935551/work/aten/src\\THC/generic/THCTensorMath.cu:26 官方还没有解决https://github.com/pytorch/pytorch/issues/27837 需要重启kernel/或者系统\n",
    "                    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7a41ca11a91943289ebcbd1c0c1dc0b6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1250), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8415f513f8694f408d269ecfeeccf317",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=352), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1a6755eb4dd04d6889059e36e95b529c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1250), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5e65ad1fc8144eb8aa62622cea3746e5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=352), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b51c9cadbb5245ac8f1a9d4e62d6a31e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1250), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b065c8bf9f314bc6b52015e3ba399814",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=352), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "for epoch in range(epochs):\n",
    "    train_loader = tqdm(train_loader)\n",
    "    train_loader.set_description('[%s%04d/%04d %s%f]' % ('Epoch:', epoch + 1, epochs, 'lr:', scheduler.get_lr()[0]))\n",
    "    train(epoch, epochs, train_loader, device, model, criterion, optimizer,scheduler, Config.tensorboard_path)\n",
    "    validate(epoch, validation_loader,device,model,criterion,Config.tensorboard_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "#模型保存\n",
    "if os.path.exists(Config.model_save_path) == False: \n",
    "    os.mkdir('./modelDict/')   \n",
    "torch.save(model.state_dict(), Config.model_save_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 测试集相关指标\n",
    "包括精确率，召回率，F1Score以及混淆矩阵，测试集准确率达到85%,精确率88%，召回率80.7%，F1分数：0.84"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_test = SentimentModel(embedding_dim=Config.embedding_dim,\n",
    "                      hidden_dim=Config.hidden_dim,\n",
    "                      pre_weight=pre_weight(len(word2ix)))\n",
    "optimizer_test = optim.Adam(model_test.parameters(), lr=Config.lr)\n",
    "scheduler_test = torch.optim.lr_scheduler.StepLR(optimizer, step_size = 10,gamma=0.1)#学习率调整\n",
    "criterion_test = nn.CrossEntropyLoss()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model_test.load_state_dict(torch.load(Config.model_save_path),strict=True)  # 模型加载"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "13420262797e41a2b2e679b31ce0786c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=24), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "confuse_meter = ConfuseMeter()\n",
    "confuse_meter = test(test_loader,device,model_test,criterion_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prec:0.880240  recall:0.807692  F1:0.842407\n"
     ]
    }
   ],
   "source": [
    "print('prec:%.6f  recall:%.6f  F1:%.6f'%(confuse_meter.pre,confuse_meter.rec, confuse_meter.F1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[147.,  20.],\n",
       "        [ 35., 167.]])"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#混淆矩阵\n",
    "confuse_meter.confuse_mat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 模型使用\n",
    "使用模型来对自己收集的豆瓣上面对《龙岭迷窟》的评论进行分类预测。第一条是好评，第二条是差评，使用自己的模型能够正确对两条评论进行分类。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict(comment_str, model, device):\n",
    "    model = model.to(device)\n",
    "    seg_list = jieba.lcut(comment_str,cut_all=False)\n",
    "    words_to_idx = []\n",
    "    for w in seg_list:\n",
    "        try:\n",
    "            index = word2ix[w] \n",
    "        except:\n",
    "            index = 0 #可能出现没有收录的词语，置为0 \n",
    "        words_to_idx.append(index)\n",
    "    inputs = torch.tensor(words_to_idx).to(device)\n",
    "    inputs = inputs.reshape(1,len(inputs))\n",
    "    outputs,_ = model(inputs, [len(inputs),])\n",
    "    pred = outputs.argmax(1).item()\n",
    "    return pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "comment_str1 = \"这一部导演、监制、男一都和《怒晴湘西》都是原班人马，这次是黄土高原上《龙岭密窟》的探险故事，有蝙蝠群、巨型蜘蛛这些让人瑟瑟发抖的元素，紧张刺激的剧情挺期待的。潘老师演技一如既往地稳。本来对姜超的印象也还在李大嘴这个喜剧角色里，居然没让人失望，还挺贴合王胖子这个角色。\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Positive\n"
     ]
    }
   ],
   "source": [
    "if (predict(comment_str1,model,device)):\n",
    "    print(\"Negative\")\n",
    "else:\n",
    "    print(\"Positive\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "comment_str2 = \"年代感太差，剧情非常的拖沓，还是冗余情节的拖沓。特效五毛，实在是太烂。潘粤明对这剧也太不上心了，胖得都能演王胖子了，好歹也锻炼一下。烂剧！\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Negative\n"
     ]
    }
   ],
   "source": [
    "if (predict(comment_str2,model,device)):\n",
    "    print(\"Negative\")\n",
    "else:\n",
    "    print(\"Positive\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
